import React, { useState, useEffect } from "react"
import { getCookie } from "../../utils/cookie"
import $ from "jquery"
import instance from "../../utils/instance"
import "./Liker.css"

function Liker(props) {
    const [voteCount, setVoteCount] = useState(props.answer.voteCount)
    const [likingActive, setLikingActive] = useState(0)
    useEffect(() => {
        let token = getCookie("token")
        let _id = props.userId
        if (_id) {
            instance.defaults.headers.common['Authorization'] = "Bearer " + token
            instance.get(`/users/${_id}/likingAnswers`).then(data => {
                let list = data.data.data
                let currentActive = list.filter(item => item._id === list[0]._id)
                if (currentActive.length > 0) {
                    setLikingActive(1)
                }
            })
        }
    }, [props.userId])
    useEffect(() => {
        if (likingActive === 1) {
            $(`#${props.answer._id}`).eq(0).addClass("active")
        } else {
            $(`#${props.answer._id}`).eq(0).removeClass("active")
        }
    }, [likingActive])
    const likingAnswer = (e) => {
        let token = getCookie("token")
        let answerId = props.answer._id
        instance.defaults.headers.common['Authorization'] = "Bearer " + token
        if (answerId) {
            if (likingActive === 0) {
                instance.put(`/users/likingAnswers/${answerId}`)
                    .then(data => {
                        if (data.data.errno === 0) {
                            setLikingActive(1)
                            setVoteCount(voteCount + 1)
                        }
                    })
            } else {
                instance.delete(`/users/likingAnswers/${answerId}`)
                    .then(data => {
                        if (data.data.errno === 0) {
                            setLikingActive(0)
                            setVoteCount(voteCount - 1)
                        }
                    })
            }
        }
    }
    const dislikingAnswer = (e) => {
        let token = getCookie("token")
        let answerId = props.answer._id
        instance.defaults.headers.common['Authorization'] = "Bearer " + token
        if (answerId) {
            instance.put(`/users/dislikingAnswers/${answerId}`).then(data => {
                if (data.data.errno === 0) {
                    likingActive === 1 ? setVoteCount(voteCount - 1) : setVoteCount(voteCount)
                    setLikingActive(0)
                }
            })
        }
    }
    return (
        <div className="question_liker">
            <p onClick={(e) => { likingAnswer(e) }} id={props.answer._id}><span className="iconfont iconshangsanjiaoxing"></span>{likingActive === 0 ? "赞成" : "已赞同"}<i>{voteCount}</i></p>
            <p onClick={(e) => { dislikingAnswer(e) }}><span className="iconfont iconbelow-s"></span>踩</p>
        </div>
    )
}

export default Liker